package com.vhall.component.framework.common.model;

import com.vhall.component.framework.common.enums.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.Serializable;

@Slf4j
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private boolean success = false;
    private String key = "success";
    private int code;
    private String msg;
    private String trace_id;

    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getTrace_id() {
        return MDC.get("traceId");
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public static <T> Result<T> success(T result) {
        Result<T> response = new Result<T>();
        response.setData(result);
        response.setMsg(HttpResponseStatus.OK.getReasonPhrase());
        response.setCode(HttpResponseStatus.OK.value());
        response.setSuccess(true);
        response.setKey("success");
        return response;
    }


    public static <T> Result<T> error(String message) {
        Result<T> response = new Result<T>();
        response.setData(null);
        response.setMsg(message);
        response.setCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.value());
        response.setSuccess(false);
        response.setKey("failed");
        return response;
    }


    public static <T> Result<T> error(Exception e) {
        Result<T> response = new Result<T>();
        response.setKey("failed");
        response.setData(null);
        if (e instanceof IllegalArgumentException) {
            response.setMsg(e.getMessage());
            response.setCode(HttpResponseStatus.BAD_REQUEST.value());
        } else {
            response.setCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.value());
            response.setMsg(e.getMessage());
            log.error("", e);
        }
        response.setSuccess(false);
        return response;
    }

    @Override
    public String toString() {
        return "Result{" + "success=" + success + ", key='" + key + '\'' + ", code=" + code + ", msg='" + msg + '\''
                + ", trace_id='" + trace_id + '\'' + ", data=" + data + '}';
    }
}

